<?php
/*
 * 商品规格
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\facade\Db;
use think\facade\Session;
use app\common\model\Sku as SkuModel;

class Sku extends AdminBase
{
    public function lists()
    {
        $authRule = collection(SkuModel::select())->toArray();
        $list = list_to_tree($authRule);
        return $this->fetch('index',['list'=>$list]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'menu');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = SkuModel::create($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了商品规格');
            $this->success('添加成功');
        }
        return $this->fetch('save',['data' => Db::table('sku')->where('status',1)->select()]);
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'menu');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = SkuModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了商品规格');
            $this->success('修改成功');
        }
        return $this->fetch('save',['list' => Db::table('sku')->find(input('id')),'data' => Db::table('sku')->where('status',1)->select()]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Db::table('sku')->where('pid',$param['id'])->find() && $this->error('当前规格下有子规格，无法删除');
            SkuModel::destroy($param['id']);
            insert_admin_log('删除了商品规格');
            $this->success('删除成功');
        }
    }


}
